import widget_base
from widget_base import Template

WidgetList = ['ImageFile']

import os
import cherrypy
import turbogears as tg

UPLOAD_DIR = cherrypy.config.get("image.uploads", os.path.join(os.getcwd(), "uploads"))
if not os.path.exists(UPLOAD_DIR):
    os.makedirs(UPLOAD_DIR)
    
LINK_DIR = cherrypy.config.get("image.link", tg.url("/static/images/"))

class ImageFile(widget_base.NodeBase):
    ContentTemplate = """
    <?python
        def GetImageAttr(Width, Height, Visible):
            ImageAttr = {}
            if Width:
                ImageAttr['width'] = Width
            if Height:
                ImageAttr['height'] = Height
            if not Visible:
                ImageAttr['style'] = 'display: none;'
            return ImageAttr
    ?>

    <img xmlns:py="http://purl.org/kid/ns#" src="${FileName}" py:attrs="GetImageAttr(Width, Height, Visible)"/>
    """
    
    FormTemplate = """
    <?python
        def GetImageAttr(Width, Height, Visible):
            ImageAttr = {}
            if Width:
                ImageAttr['width'] = Width
            if Height:
                ImageAttr['height'] = Height
            return ImageAttr
    ?>
    <span xmlns:py="http://purl.org/kid/ns#">
        <img xmlns:py="http://purl.org/kid/ns#" src="${FileName}" py:attrs="GetImageAttr(Width, Height, Visible)"/>
        <form id="image_updoad${ID}" method="post" action="modify" enctype="multipart/form-data" target="upload">
            Image link:<input type="text" value="${FileName}" />
            <br />
            Upload:<input type="file" name="modify_file" />
            <br />
            Width:<input type="text" value="${Width}" name="modify_width" />
            <br />
            Height:<input type="text" value="${Height}" name="modify_height" />
            <br />
            Visible:<input type="checkbox" name="modify_visible" value="true" py:attrs="{'checked': 'checked'} if Visible else {}"/>
            <br />
            <input type="hidden" id="image_article_id${ID}" name="article_id" />
            <input type="hidden" name="id" value="${ID}" />
            <a href="javascript: UploadImage(${ID});">Modify</a>
            |
            <a href="javascript: LoadCommandResult('cancel', {'id': '${ID}', 'tocallback_prefix': 'content'});">Cancel</a>
        </form>
        <iframe id="upload" name="upload" src="about:blank" width="1" height="1" frameborder="0" onLoad="FinishUpload(${ID})"></iframe>
    </span>
    """
    
    def __init__(self):
        widget_base.NodeBase.__init__(self)
        self.Data['original_file_name'] = ''
        self.Data['file_name'] = ''
        self.Data['width'] = ''
        self.Data['height'] = ''
        self.Data['visible'] = True
        
    def __deepcopy__(self, memo):
        import shutil
        from copy import deepcopy
        
        NewImage = widget_base.NodeBase.__deepcopy__(self, memo)
        
        NewFileName = self.GetImageFileName(NewImage.Data['file_name'])
        ScrFilePath = os.path.join(os.getcwd(), UPLOAD_DIR, NewImage.Data['file_name'])
        DestFilePath = os.path.join(os.getcwd(), UPLOAD_DIR, NewFileName)
        
        shutil.copyfile(ScrFilePath, DestFilePath)
        
        NewImage.Data['file_name'] = NewFileName
        
        return NewImage
        
    @Template(source = ContentTemplate)
    def RenderContent(self, DisplayEditable = False):
        Dictionary = {}
        if self.Data['file_name']:
            Dictionary['FileName'] = tg.url(LINK_DIR + self.Data['file_name'])
        else:
            Dictionary['FileName'] = ''
            
        Dictionary['Width'] = self.Data['width']
        Dictionary['Height'] = self.Data['height']
        Dictionary['Visible'] = self.Data['visible']
        Dictionary['ID'] = self.ID
        return Dictionary
    
    @Template(source = FormTemplate)
    def RenderForm(self):
        Dictionary = {}
        if self.Data['file_name']:
            Dictionary['FileName'] = tg.url(LINK_DIR + self.Data['file_name'])
        else:
            Dictionary['FileName'] = ''
            
        Dictionary['Width'] = self.Data['width']
        Dictionary['Height'] = self.Data['height']
        Dictionary['Visible'] = self.Data['visible']
        Dictionary['ID'] = self.ID
        return Dictionary
    
    @staticmethod
    def RenderHeader(DisplayEditable = False):
        if DisplayEditable:
            import turbogears
            Result = """<script type="text/javascript" src="%s"></script>\n""" % turbogears.url('/static/javascript/image.js')
            return Result
        return ''
    
    def GetImageFileName(self, FileName):
        """Get a unique image file name

        @param FileName: Original file name 
        @return: A unique image file name
        """
        import datetime
        
        Extension = os.path.splitext(FileName)[1]
        
        FileNamePrefix = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        Suffix = 0
        
        while 1:
            NewFileName = "%s_%d%s" % (FileNamePrefix, Suffix, Extension)
            FilePath = os.path.join(os.getcwd(), UPLOAD_DIR, NewFileName)
            Suffix += 1
            if not os.path.exists(FilePath):
                break
            
        return NewFileName
    
    def Modify(self, *Args, **Kwargs):
        UploadFile = Kwargs['file']
        self.Data['width'] = Kwargs['width']
        self.Data['height'] = Kwargs['height']
        if Kwargs.get('visible') and Kwargs.get('visible') == 'true':
            self.Data['visible'] = True
        else:
            self.Data['visible'] = False
        
        if UploadFile.filename:
        
            NewFileName = self.GetImageFileName(UploadFile.filename)
            FilePath = os.path.join(os.getcwd(), UPLOAD_DIR, NewFileName)
    
            Data = Kwargs['file'].file.read()
            File = open(FilePath, 'wb')
            File.write(Data)
            File.close()
            
            self.Release()
            
            self.Data['original_file_name'] = UploadFile.filename
            self.Data['file_name'] = NewFileName
    
    def Release(self):
        #if self.Data['file_name']:
        #    FilePath = os.path.join(os.getcwd(), UPLOAD_DIR, self.Data['file_name'])
        #    os.remove(FilePath)
        
        try:
            if self.Data['file_name']:
                FilePath = os.path.join(os.getcwd(), UPLOAD_DIR, self.Data['file_name'])
                os.remove(FilePath)
        except:
            pass